import Vue from 'vue'
import Vuex from '../vuex'
// 默认会执行当前插件的install方法
Vue.use(Vuex)

function logger(store) {
  let preState = JSON.stringify(store.state)
  store.subscribe((mutation, newState) => {
    console.log(preState)
    console.log(mutation)
    console.log(JSON.stringify(newState))
    preState = JSON.stringify(newState)
  })
}
function persists(store) {
  const local = localStorage.getItem('VUEX_STATE')
  if (local) {
    store.replaceState(JSON.parse(local))
  }
  store.subscribe((mutation, state) => {
    localStorage.setItem('VUEX_STATE', JSON.stringify(state))
  })
}
// 通过 Vuex 中的一个属性 Store 创建一个实例
const store = new Vuex.Store({
  strict: true,
  plugins: [logger, persists],
  modules: {
    a: {
      namespaced: true,
      state: {
        age: 'a100'
      },
      mutations: {
        syncChange() {
          console.log('a-syncChange')
        }
      }
    },
    b: {
      namespaced: true,
      state: {
        age: 'b100'
      },
      mutations: {
        syncChange() {
          console.log('b-syncChange')
        }
      },
      modules: {
        c: {
          namespaced: true,
          state: {
            age: 'c100'
          },
          mutations: {
            syncChange() {
              console.log('c-syncChange')
            }
          }
        }
      }
    }
  },
  // 单一数据源
  state: {
    age: 10
  },
  getters: {
    myAge(state) {
      return state.age * 2
    }
  },
  mutations: {
    syncChange(state, { step }) {
      // state.age += step
      setTimeout(() => {
        state.age += step
      }, 1000)
    },
    asyncChange(state, { step }) {
      state.age -= step
    }
  },
  actions: {
    asyncChange({ commit }, { step }) {
      setTimeout(() => {
        commit('asyncChange', { step })
      }, 500)
    }
  }
})

store.registerModule('d', {
  state: {
    age: 'd100'
  }
})

export default store
